#!/bin/bash

source commonlib.sh

masters=(
    192.168.122.101
    192.168.122.102
    192.168.122.103
)

workers=(
    192.168.122.201
    192.168.122.202
    192.168.122.203
    192.168.122.204
    192.168.122.205
    192.168.122.206
)

function copy_sshkey() {
    local ip=$1
    local password=$2
    if [ -z $ip ]; then
        log ERROR "should input ip address as 2nd input"
        exit 1
    fi
    log INFO "Copying ssh-key from $ip"
    if [ -z $password ]; then
        log ERROR "should input password as 1st input"
        exit 1
    fi
    # 拷贝对应 IP 的 ssh-key 到本机实现免密登陆
    # openEuler 缺少 sshpass 包,只能手动写 expect
    #sshpass -f $pass_file ssh-copy-id root@$ip

    expect -c "
        set timeout 60
        spawn ssh-copy-id root@$ip
        expect {
            "*\(yes/no*" { exp_send "yes\\r"; exp_continue }
            "*assword*" { exp_send "$password\\r" }
            "*exist*" { interact; exit 0 }
        }
        expect eof
    " > /dev/null 2>&1
}

# 收集虚拟机的公钥以便 host 上免密登陆虚拟机 
function collect_sshkey() {
    # 先本机生成 ssh-key, 如果已经生成,则会自动跳过 
    cat /dev/zero | ssh-keygen -q -N ""; echo
    # 开始拷贝
    for ip in ${masters[@]}; do
        copy_sshkey $ip "Huawei12#$"
    done
    for ip in ${workers[@]}; do
        copy_sshkey $ip "Huawei12#$"
    done
    # TODO: 密码明文解决
}

# 生成 hosts 文件
# input: hosts file path
function gen_hosts() {
    local host_path=$1
    if [ -f $host_path ]; then
        rm -f $host_path
        log INFO "Remove old hosts file"
    fi
    for i in $(seq 1 ${#masters[*]}); do
        echo "master$i ${masters[$((i-1))]}" >> $host_path
    done
    for i in $(seq 1 ${#workers[*]}); do
        echo "worker$i ${workers[$((i-1))]}" >> $host_path
    done
    log INFO "Generated hosts files: $(realpath ${host_path})"
}

# scp 拷贝文件/文件夹命令
function scp_cmd() {
    local file_path=$(realpath $1)
    local target_ip=$2
    local target_path=$3
    if [ -d "$file_path" ]; then
        is_dir="-r"
    elif [ -f "$file_path" ]; then
        is_dir=""
    else
        log ERROR "Wrong file path: $file_path"
        exit 1
    fi

    log INFO "Transporting file ${file_path} to $target_ip:$target_path"
    scp $is_dir $file_path $target_ip:$target_path
}

function transport_to_masters() {
    local file=$1
    for mip in ${masters[@]}; do
        scp_cmd $file $mip "/root"
    done
}

function transport_to_workers() {
    local file=$1
    for wip in ${workers[@]}; do
        scp_cmd $file $wip "/root"
    done
}



function transport_2_all() {
    local file=$1
    transport_to_masters $file
    transport_to_workers $file
}

# 使用须知
# 1. 确保虚拟机已经设置好了静态 IP
# 2. 修改文件最开始的 masters 和 workers IP
collect_sshkey
gen_hosts hosts
transport_to_workers /data/lx/vm/script
